import { SOURCES_LIST, ADD_SOURCES, GET_SOURCE, BATCH_ADD_SOURCES, REMOVE_SOURCES, UPDATE_SOURCE } from './channel'
import db from './db'
import fetch from 'node-fetch'

export default {
  [SOURCES_LIST]: async () => {
    const result = await db.sources().find({ enable: true }).sort({ "weight": -1 })
    return result
  },
  [ADD_SOURCES]: async (data: any) => {
    const result = await db.sources().insert(data)
    return result
  },
  [GET_SOURCE]: async (query: any) => {
    const result = await db.sources().findOne(query)
    return result
  },
  [REMOVE_SOURCES]: async (data: any) => {
    const result = await db.sources().remove(data, {})
    return result
  },
  [BATCH_ADD_SOURCES]: async (url: string) => {
    const response = await fetch(url)
    const sources = await response.json()
    for (const source of sources) {
      const result = await db.sources().findOne({ bookSourceUrl: source.bookSourceUrl })
      if (result) {
        await db.sources().update({ _id: result._id }, { $set: source })
      } else {
        await db.sources().insert(source)
      }
    }
    return true
  },
  [UPDATE_SOURCE]: async (params: any) => {
    const { _id, ...update } = params
    const result = await db.sources().update({ _id: _id }, { $set: update })
    return result
  }
}
